//
//  AppDelegate.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/11.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "AppDelegate.h"

#import <UserNotifications/UserNotifications.h>
#import <UMSocialCore/UMSocialCore.h>
#import <Bugly/Bugly.h>

#import "DownloadListDAO.h"
#import "PhoneInfo.h"
#import "IAPManager.h"

#import "UMessage.h"
#import "IGAvPlayerManager.h"

#import "OrderPayManager.h"
#import "XHPKit.h"

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@property (nonatomic, strong) NSDictionary *userInfo;

@end

@implementation AppDelegate

- (void)initAppWithOP:(NSDictionary *)launchOptions {
    
    
    BOOL hasInApp = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasInApp"];
    
    if (hasInApp) {
        
        [NetAPIManager getAppVersionBlock:nil];
        [[IAPManager sharedManager] startManager];
        [self configCacheData];
        [self setupUMeng:launchOptions];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSInteger openTimes = [[NSUserDefaults standardUserDefaults] integerForKey:@"openTimes"];
            [[NSUserDefaults standardUserDefaults] setInteger:(openTimes + 1) forKey:@"openTimes"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        });
    }
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        [AppManager sharedManager].networkState = status;
        
        if (status != AFNetworkReachabilityStatusNotReachable && !hasInApp) {
            
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDate *date = [NSDate date];
                    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"insertAppTime"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                });
                
                [NetAPIManager getAppVersionBlock:nil];
                [self setupUMeng:launchOptions];
            });
        }
    }];
}
//// ------------------设置魔窗 统计渠道用-------------------------------------
//- (void)setupMW {
//
//    [MWApi registerApp:MW_KEY];
//
//    [MWApi registerMLinkHandlerWithKey:@"channel" handler:^(NSURL *url, NSDictionary *params) {
//        //自行处理跳转逻辑，示例如下：
//
//        NSString *chid = params[@"chid"];
//
//        NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
//
//        if (chid) {
//
//            [UserManager sharedManager].chid = chid;
//            [daDict setObject:chid forKey:@"chid"];
//            [MWApi setChannelId:chid];
//        }
//        [NetAPIManager postPhoneData:daDict];
//    }];
//
//
//    [MWApi registerMLinkHandlerWithKey:@"detail" handler:^(NSURL *url, NSDictionary *params) {
//        //自行处理跳转逻辑，示例如下：
//
//        NSString *lineid = params[@"lineid"];
//
//        NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
//
//        if (lineid) {
//
//            [daDict setObject:lineid forKey:@"opendetailid"];
//
//            Message *obj = [Message new];
//            obj.relationid = lineid;
//            obj.type = @"line";
//            [AppManager sharedManager].pushObj = obj;
//
//            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshMainVCNotif object:nil];
//        }
//        [NetAPIManager postPhoneData:daDict];
//
//    }];
//}
// ------------------初始化友盟-------------------------------------
- (void)setupUMeng:(NSDictionary *)launchOptions {
    
    [[LocationManager sharedManager] startUpdatingLocation];
    
    UMConfigInstance.appKey = UMENG_APPKEY;
    UMConfigInstance.channelId = [UserManager sharedManager].chid ? [UserManager sharedManager].chid : @"AppStore";
    
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    [MobClick setAppVersion:kVersion];
    
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMENG_APPKEY];
    
    
    [UMessage startWithAppkey:UMENG_APPKEY launchOptions:launchOptions httpsenable:YES];
    [UMessage setBadgeClear:YES];
    [UMessage setAutoAlert:NO];
    
    //注册通知，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        
        UNAuthorizationOptions types10 = UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
        
        [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
            
            if (granted) {
                //点击允许
                //这里可以添加一些自己的逻辑
            } else {
                //点击不允许
                //这里可以添加一些自己的逻辑
            }
        }];
    }
    
    //    初始化分享，登录平台
    [self configUSharePlatforms];
    
}

- (void)configUSharePlatforms {
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:UMENG_WX_APPID appSecret:UMENG_WX_APPSECRET redirectURL:kRedirectURL];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:UMENG_QQ_APPID  appSecret:nil redirectURL:kRedirectURL];
    
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:UMENG_WB_APPKEY  appSecret:UMENG_WB_APPSECRET redirectURL:@"https://api.weibo.com/oauth2/default.html"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Twitter appKey:UMENG_Twitter_APPID  appSecret:UMENG_Twitter_APPSECRET redirectURL:nil];
    
    /* 设置Facebook的appKey和UrlString */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Facebook appKey:UMENG_FB_APPID  appSecret:nil redirectURL:kRedirectURL];
    
    /* 设置bugly */
    [Bugly startWithAppId:BUGLY_APPID];
}


/**
 应用升级，清楚缓存 （防止数据结构发生变化，造成崩溃）
 */
- (void)configCacheData {
    
    [[DownloadManager sharedManager] beginAllDownloading];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self initAppWithOP:launchOptions];
    
    return YES;
}


//---------------------------- 第三方登录回调
// 仅支持iOS9以上系统，iOS8及以下系统不会回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    
    return [self callbackWithURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation {
    
    return [self callbackWithURL:url];
}

// 支持目前所有iOS系统
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    return [self callbackWithURL:url];
}

- (BOOL)callbackWithURL:(NSURL *)url {
    
    [self channelTrackingWithUrl:url];
    
    BOOL b1 = [[XHPKit defaultManager] handleOpenURL:url];
    
    BOOL b2 = [[UMSocialManager defaultManager] handleOpenURL:url];
    
    return b1 || b2;
}

- (void)channelTrackingWithUrl:(NSURL *)url {
    
    
    if (![url.absoluteString containsString:@"sendcookie"]) {
        return;
    }
    
    NSDictionary *params = [IGUtil parseURLParamsWithURL:url];
    
    if (params.count == 0 || ![params containsObjectForKey:@"chid"]) {
        return;
    }
    
    NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
    
    [UserManager sharedManager].chid = params[@"chid"];
    
    [daDict setDictionary:params];
    
    [NetAPIManager postPhoneData:daDict];
    
}



- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler {
    
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        
        NSURL *webpageURL = userActivity.webpageURL;
        
        NSDictionary *params = [IGUtil parseURLParamsWithURL:webpageURL];
        
        if (params.count == 0) {
            return NO;
        }
        
        Message *obj = [Message new];
        obj.relationid = params[@"id"];
        obj.type = params[@"type"];
        [AppManager sharedManager].pushObj = obj;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshMainVCNotif object:nil];
        
    }
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    [self resignFirstResponder];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    if (event.type == UIEventTypeRemoteControl) {
        
        switch (event.subtype) { // 得到事件类型
                
            case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6
                
                [[IGAvPlayerManager shareManeger] pause];
                // 调用你所在项目的暂停按钮的响应方法 下面的也是如此
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                
                [[IGAvPlayerManager shareManeger] previous];
                break;
                
            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                [[IGAvPlayerManager shareManeger] next];
                
                break;
                
            case UIEventSubtypeRemoteControlPlay: //播放
                [[IGAvPlayerManager shareManeger] play];
                break;
                
            case UIEventSubtypeRemoteControlPause: // 暂停 ios7
                // [self actionStopButton:self.musicViewNew.stopButton];
                [[IGAvPlayerManager shareManeger] pause];
                break;
                
            default:
                
                break;
        }
    }
}

- (void)pushWithUserInfo:(NSDictionary *)userInfo {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [UMessage sendClickReportForRemoteNotification:userInfo];
    self.userInfo = userInfo;
    
    Message *msg = [Message new];
    msg.title = userInfo[@"aps"][@"alert"][@"title"];
    msg.content = userInfo[@"aps"][@"alert"][@"body"];
    msg.type = userInfo[@"type"];
    msg.relationid = userInfo[@"relationid"];
    
    [AppManager sharedManager].pushObj = msg;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshMainVCNotif object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kReloadUserDataNotif object:nil];
}

//iOS10以前接收的方法
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)(void))completionHandler {
    
    [self pushWithUserInfo:userInfo];
}
//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    [self pushWithUserInfo:userInfo];
}

//iOS10新增：处理前台收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge);
    
    [self pushWithUserInfo:userInfo];
}

//iOS10新增：处理后台点击通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于后台时的远程推送接受
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            
        }else{
            //应用处于后台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
    [self pushWithUserInfo:userInfo];
}
@end

